package com.example.productservice.controller;

import com.example.productservice.bean.Product;
import com.example.productservice.service.ProductService;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/product")
public class ProductController {
    @Autowired
    private ProductService service;

    @RequestMapping("/findall")
    public List<Product> findAll() { return service.findAll(); }

    @HystrixCommand(fallbackMethod = "findByIdFallback")
    @RequestMapping("/findbyid/{id}")
    public Product findById(@PathVariable Long id) throws Exception {
        Product product = service.findById(id);
        if (product == null) throw new Exception("Product not found");
        return product;
    }

    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public int createProduct(@RequestBody Product product) {
        return service.createProduct(product);
    }

    public Product findByIdFallback(Long id) {
        Product product = new Product();
        product.setId(-1L);
        product.setName("Not found");
        return product;
    }
}